package com.cqndt.visual.socket;

import com.cqndt.visual.vo.FlightDataVo;
import com.cqndt.visual.service.BusinessService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created By marc
 * Date: 2021/5/13  16:58
 * Description:
 *
 * uavSn=无人机系列号 code=（0：无消息 1：控制面板发送消息 2事件列表消息
 * channelType=（0：app端 1：pc端））
 */
@ServerEndpoint("/fightData/{uavSn}/{code}/{channelType}")
@Component
public class WebSocketServer {

    private final static Logger log = LoggerFactory.getLogger(WebSocketServer.class);

    /**concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。*/
    private static ConcurrentHashMap<String,WebSocketServer> webSocketMap = new ConcurrentHashMap<>();

    /**与某个客户端的连接会话，需要通过它来给客户端发送数据*/
    private Session session;

    private String uavSn="";

    private String code="";

    private String channelType="";

    public static WebSocketServer webSocketServer;

    @Autowired
    BusinessService businessService;

    @PostConstruct
    public void init() {
        webSocketServer = this;
        webSocketServer.businessService = this.businessService;

    }


    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(Session session,@PathParam("uavSn") String uavSn,@PathParam("code") String code,@PathParam("channelType") String channelType) {
        this.session = session;
        this.uavSn=uavSn;
        this.code = code;
        this.channelType = channelType;
        if(webSocketMap.containsKey(uavSn+"-"+channelType)){
            webSocketMap.remove(uavSn+"-"+channelType);
            webSocketMap.put(uavSn+"-"+channelType,this);
            //加入set中
        }else{
            webSocketMap.put(uavSn+"-"+channelType,this);
            //加入set中
        }
        log.info("用户连接:"+uavSn+"-"+channelType);
        try {
            if("1".equals(code)){
//                if("0".equals(channelType)){
//                    webSocketServer.businessService.sendMessage(uavSn+"-"+channelType);
//                }
                sendMessage1();
            }else if("2".equals(code)){
                sendMessage2();
            }else{
                sendMessage("连接成功");
            }
        } catch (IOException e) {
            log.error("用户:"+uavSn+"-"+channelType+",网络异常!!!!!!");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        if(webSocketMap.containsKey(uavSn+"-"+channelType)){
            webSocketMap.remove(uavSn+"-"+channelType);
        }
        log.info("用户退出:"+uavSn+"-"+channelType);
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息*/
    @OnMessage
    public void onMessage(String message, Session session) {
    }

    /**
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("用户错误:"+this.uavSn+"-"+channelType+",原因:"+error.getMessage());
        error.printStackTrace();
    }
    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    public void sendMessage2() throws IOException {
        List<FlightDataVo> list = new ArrayList<FlightDataVo>();
        FlightDataVo dto = new FlightDataVo();
        dto.setCode("0");
        dto.setUavLatitude("21.54512");
        dto.setUavLongitude("100.74156");
        dto.setAirSpeed(Math.random()*100+"");
        dto.setLandSpeed(Math.random()*100+"");
        dto.setUavFlyingHeight(Math.random()*100+"");
        list.add(dto);
        dto = new FlightDataVo();
        dto.setCode("0");
        dto.setUavLatitude("21.54528");
        dto.setUavLongitude("100.74175");
        dto.setAirSpeed(Math.random()*100+"");
        dto.setLandSpeed(Math.random()*100+"");
        dto.setUavFlyingHeight(Math.random()*100+"");
        list.add(dto);
        dto = new FlightDataVo();
        dto.setCode("0");
        dto.setUavLatitude("21.54536");
        dto.setUavLongitude("100.74193");
        dto.setAirSpeed(Math.random()*100+"");
        dto.setLandSpeed(Math.random()*100+"");
        dto.setUavFlyingHeight(Math.random()*100+"");
        list.add(dto);
        dto = new FlightDataVo();
        dto.setCode("0");
        dto.setUavLatitude("21.54538");
        dto.setUavLongitude("100.74219");
        dto.setAirSpeed(Math.random()*100+"");
        dto.setLandSpeed(Math.random()*100+"");
        dto.setUavFlyingHeight(Math.random()*100+"");
        list.add(dto);
        dto = new FlightDataVo();
        dto.setCode("0");
        dto.setUavLatitude("21.54536");
        dto.setUavLongitude("100.74239");
        dto.setAirSpeed(Math.random()*100+"");
        dto.setLandSpeed(Math.random()*100+"");
        dto.setUavFlyingHeight(Math.random()*100+"");
        list.add(dto);
        dto = new FlightDataVo();
        dto.setUavLatitude("21.5453");
        dto.setUavLongitude("100.74259");
        dto.setAirSpeed(Math.random()*100+"");
        dto.setLandSpeed(Math.random()*100+"");
        dto.setUavFlyingHeight(Math.random()*100+"");
        list.add(dto);

        dto = new FlightDataVo();
        dto.setCode("0");
        dto.setUavLatitude("21.54521");
        dto.setUavLongitude("100.74282");
        dto.setAirSpeed(Math.random()*100+"");
        dto.setLandSpeed(Math.random()*100+"");
        dto.setUavFlyingHeight(Math.random()*100+"");
        list.add(dto);

        dto = new FlightDataVo();
        dto.setCode("0");
        dto.setUavLatitude("21.54510");
        dto.setUavLongitude("100.74305");
        dto.setAirSpeed(Math.random()*100+"");
        dto.setLandSpeed(Math.random()*100+"");
        dto.setUavFlyingHeight(Math.random()*100+"");
        list.add(dto);

        dto = new FlightDataVo();
        dto.setCode("0");
        dto.setUavLatitude("21.54501");
        dto.setUavLongitude("100.74324");
        dto.setAirSpeed(Math.random()*100+"");
        dto.setLandSpeed(Math.random()*100+"");
        dto.setUavFlyingHeight(Math.random()*100+"");
        list.add(dto);

        dto = new FlightDataVo();
        dto.setCode("0");
        dto.setUavLatitude("21.54491");
        dto.setUavLongitude("100.74342");
        dto.setAirSpeed(Math.random()*100+"");
        dto.setLandSpeed(Math.random()*100+"");
        dto.setUavFlyingHeight(Math.random()*100+"");
        list.add(dto);

        dto = new FlightDataVo();
        dto.setCode("0");
        dto.setUavLatitude("21.54462");
        dto.setUavLongitude("100.74378");
        dto.setAirSpeed(Math.random()*100+"");
        dto.setLandSpeed(Math.random()*100+"");
        dto.setUavFlyingHeight(Math.random()*100+"");
        list.add(dto);
        System.out.println("列表推送消息");
        for (FlightDataVo vo:list) {
            if(webSocketMap.containsKey(uavSn+"-"+channelType)){
                webSocketMap.get(uavSn+"-"+channelType).sendMessage(vo.toString1());
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void sendMessage1() throws IOException {
        System.out.println("控制面板推送消息");
        while (true){
            String message = "{ " +
                    "\"aiPeopleNum\":0, " +
                    "\"airSpeed\":"+Math.random()*100+", " +
                    "\"angle\":2.0865633, " +
                    "\"appVersions\":\"2.1.0\", " +
                    "\"attitude\":313.45502, " +
                    "\"batteryWarning\":0, " +
                    "\"current\":0, " +
                    "\"electricQuantity\":0, " +
                    "\"flyHeading\":0, " +
                    "\"gpsNum\":\"0\", " +
                    "\"landSpeed\":"+Math.random()*100+", " +
                    "\"orienteering\":\"无效\", " +
                    "\"pitchangle\":0, " +
                    "\"podLatitude\":"+Math.random()*100+", " +
                    "\"podLongitude\":"+Math.random()*100+", " +
                    "\"pressure\":7, " +
                    "\"remoteControlSignal\":0, " +
                    "\"roll\":0, " +
                    "\"temperature\":0, " +
                    "\"uavFlyTime\":718, " +
                    "\"uavFlyingHeight\":"+Math.random()*100+", " +
                    "\"uavGpsTime\":1445109878, " +
                    "\"uavLatitude\":"+Math.random()*100+", " +
                    "\"uavLongitude\":"+Math.random()*100+", " +
                    "\"uavModel\":\"E260-SECURITY\", " +
                    "\"uavSn\":\"4MFCC12004003G\", " +
                    "\"uavFirmwareVersion\":\"1.10.0 (1127)\", " +
                    "\"verticalSpeed\":0.012, " +
                    "\"videoSignal\":0, " +
                    "\"voltage\":23.65966796875, " +
                    "\"aiCarNum\":0, " +
                    "\"yaw\":0 " +
                    "}";
            if(null == uavSn || !webSocketMap.containsKey(uavSn+"-"+channelType)){
                break;
            }
            this.session.getBasicRemote().sendText(message);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }


    /**
     * 发送自定义消息
     * */
    public static void sendInfo(String message,@PathParam("uavSn") String uavSn) throws IOException {
        if(null != uavSn && webSocketMap.containsKey(uavSn)){
            log.info("发送消息到:"+uavSn+"，报文:"+message);
            webSocketMap.get(uavSn).sendMessage(message);
        }else{
            log.error("用户"+uavSn+",不在线！");
        }
    }


}
